/*
 * @Author: xyf
 * @Date: 2021-11-22 21:56:38
 * @LastEditTime: 2021-12-15 23:53:07
 * @LastEditors: xyf
 * @Description: 请求封装
 */

import store from "@/store";
import config from "@/config";
import Request from "luch-request";
const whiteList = [
 "/applet/client/login",
 "/applet/agent/login",
 "/applet/goods/page",
 "/applet/goods/",
 "/applet/PageData/getPageData"
]
const service = new Request();
/* 全局配置 */

service.setConfig((config) => {
  config.baseURL = config.baseApi
  return config;
});

/* 请求拦截器 */
service.interceptors.request.use(
  config => {
	const token = uni.getStorageSync('token');
	var pass= false;
	for(var i = 0;i<whiteList.length;i++){
		if(config.url.indexOf(whiteList[i]) != -1){
			pass = true;
		}
	}
	if(config.url.indexOf('agent')>-1){
		const sysToken = uni.getStorageSync('sysToken');
		if(!sysToken&&!pass){
			// uni.redirectTo({
			// 	//关闭当前页面，跳转到应用内的某个页面。
			// 	url:'/pages-merchant/login/index'
			// });
			// uni.redirectTo({
			// 	url:'/pages-merchant/login/index'
			// });
			uni.navigateTo({
				url:'/pages/agent/pages/login/index'
			})
			return
		}
		config.header['Authorization'] = sysToken
		
	}
	if(!token&&!pass){
		
		uni.navigateTo({
			url:'/pages/login/index'
		})
		return 
	}
	config.header['token'] = token
    return config;
  },
  error => {
	console.log('请求出错',error)
    return Promise.reject(error);
  }
);

/* 响应拦截器 */
service.interceptors.response.use(
  (response) => {
    const { data } = response;
    if(data.httpCode === 200){
		return Promise.resolve(data.data)
    }else if(data.httpCode === 401){
		// store.dispatch('login').then(res => {
		// 	console.log("res=", res)
		// });
		uni.navigateTo({
			url:'/pages/login/index'
		})
		return
	}else{
		return Promise.reject(data)
    }
  },
  (error) => {
	console.log("响应出错",error)
    return Promise.reject(error)
  }
);

/* 请求核心函数 */
function request(options) {
  options.method = options.method || "get";
  if (options.method.toLowerCase() === "get") options.params = options.data;

  let isMock = config.mock;
  if (typeof options.mock != "undefined") {
    isMock = options.mock;
  }

  // 避免生产环境调用mock
  if (config.env === "production") {
    service.config.baseURL = config.baseApi;
  } else {
    service.config.baseURL = isMock ? config.mockApi : config.baseApi;
  }
  return service.request(options);
}

export default request;
